package com.math.util;

import lombok.extern.slf4j.Slf4j;

import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
@Slf4j
public class ConvertUtil {


    //设置xls依赖文件的路径
    public static URIResolver r = (href, base) -> {
        InputStream inputStream = ConvertUtil.class.getResourceAsStream("/formula/xsl/xsltml_2.1.2/" + href);
        return new StreamSource(inputStream);
    };

    /**
     * <p>Description: office mathml转为mml </p>
     *
     * @param xml
     * @return
     */
    public static String convertOMMLToMML(String xml) {
        return xslConvert(xml, "/formula/xsl/OMML2MML.XSL", null);
    }

    /**
     * mathml to latex
     *
     * @param mml mathml 公式源码
     * @return java.lang.String
     */
    public static String convertMMLToLatex(String mml) {
        return xslConvert(mml, "/formula/xsl/xsltml_2.1.2/mmltex.xsl", r);
    }

    /**
     * xsl Convert
     *
     * @param formula     公式
     * @param uriResolver 转换器
     * @return java.lang.String
     * @author YangXinFu
     */
    public static String xslConvert(String formula, String xslPath, URIResolver uriResolver) {
        TransformerFactory tFac = TransformerFactory.newInstance();
        if (uriResolver != null) tFac.setURIResolver(uriResolver);
        InputStream inputStream = ConvertUtil.class.getResourceAsStream(xslPath);
        StreamSource xslSource = new StreamSource(inputStream);
        StringWriter writer = new StringWriter();
        try {
            Transformer t = tFac.newTransformer(xslSource);
            Source source = new StreamSource(new StringReader(formula));
            Result result = new StreamResult(writer);
            t.transform(source, result);
        } catch (TransformerException e) {
            log.warn("公式转换失败。",e);
            return "";
        }
        return writer.getBuffer().toString();
    }


}
